package main

import "smeb.xyz/pub/websocket-subandpub-cluster/internal/handlerwebsocket/protos"

// 工作池
const NumWorkers = 10

// 通道容量
const NumChannel = 10

var Tasks chan Job = make(chan Job, NumChannel)

var SomeoneTasks chan SomeoneJob = make(chan SomeoneJob, NumChannel)

var SomebodyTasks chan SomebodyJob = make(chan SomebodyJob, NumChannel)

// Worker 表示工作者，每个工作者都可以处理一个任务。
// Job 表示一个工作任务。
type Job struct {
	ChannelSubServer *[]string
	Data             *[]byte
	Channel          *string
	Sender           *uint64
}

type SomeoneJob struct {
	ChannelSubServer *[]string
	Data             *[]byte
	Channel          *string
	Member           *uint64
	Sender           *uint64
}

type SomebodyJob struct {
	ChannelSubServer *[]string
	Data             *[]byte
	Channel          *string
	Members          *[]uint64
	Sender           *uint64
}

func init() {
	// 启动多个工作者协程来处理任务。
	for i := 1; i <= NumWorkers; i++ {
		go worker(Tasks)
		go SomeoneWorker(SomeoneTasks)
		go SomebodyWorker(SomebodyTasks)
	}
}

func AddOneTaskToQueue(task Job) {
	Tasks <- task
}

func worker(jobPool <-chan Job) {
	for job := range jobPool {

		for _, channelSub := range *job.ChannelSubServer {

			if channelSub == "const" {
				continue
			}

			RpcPublishRpcMsg(channelSub, &protos.PublishToChannelRequest{
				Channel: *job.Channel,
				Data:    *job.Data,
				Sender:  *job.Sender,
			})
		}
	}
}

func AddOneSomeoneTaskToQueue(task SomeoneJob) {
	SomeoneTasks <- task
}

func SomeoneWorker(jobPool <-chan SomeoneJob) {
	for job := range jobPool {

		for _, channelSub := range *job.ChannelSubServer {

			if channelSub == "const" {
				continue
			}

			RpcUserSomeoneMessage(channelSub, &protos.PublishToSomeoneInChannelRequest{
				Channel:  *job.Channel,
				Data:     *job.Data,
				Receiver: *job.Member,
				Sender:   *job.Sender,
			})
		}
	}
}

func AddOneSomebodyTaskToQueue(task SomebodyJob) {
	SomebodyTasks <- task
}

func SomebodyWorker(jobPool <-chan SomebodyJob) {
	for job := range jobPool {

		for _, channelSub := range *job.ChannelSubServer {

			if channelSub == "const" {
				continue
			}

			RpcUserSomebodyMessage(channelSub, &protos.PublishToSomebodyInChannelRequest{
				Channel:   *job.Channel,
				Receivers: *job.Members,
				Data:      *job.Data,
				Sender:    *job.Sender,
			})
		}
	}
}
